<?php
/**
 * Admin utils
 *
 * @author Anton
 */
//var_dump(Zend_Auth::getInstance()->getIdentity());
class Lemar_Admin
{
	/**
	 * Error messages
	 * @var array
	 */
	private static $_aErrorMessages = array();
	
    public static function getErrorMessages()
    {
    	return self::$_aErrorMessages;
    }
    
    public static function setErrorMessages($aErrorMessages)
    {
    	self::$_aErrorMessages = $aErrorMessages;
    }
	
	/**
	 * Checks if admin is logged in
	 * @return bool
	 */
	public static function isLogged()
	{
		$oAuth = Zend_Auth::getInstance();
		if ($oAuth->hasIdentity())
		{
			$aIdentity = $oAuth->getIdentity();
			if ( !empty($aIdentity['Admin_id']) )
			{
				return true;
			}
		}
		else
		{
			return false;
		}
		// return Zend_Auth::getInstance()->hasIdentity();
	}
	
	/**
	 * Returns logged admin
	 * @return models_Admin|null
	 */
	public static function getLoggedAdmin()
	{
		if ( self::isLogged() )
		{
			$aIdentity = Zend_Auth::getInstance()->getIdentity();
			return models_AdminMapper::findById($aIdentity['Admin_id']);
		}
		else
		{
			return null;
		}
	}
	
	/**
	 * Returns logged admin id
	 * @return int|null
	 */
	public static function getLoggedAdminId()
	{
		if ( self::isLogged() )
		{
			$aIdentity = Zend_Auth::getInstance()->getIdentity();
			return $aIdentity['Admin_id'];
		}
		else
		{
			return null;
		}
	}

	/**
	 * Sets admin logged in
	 *
	 * @param int $iAdminId
	 */
	public static function setLogged($iAdminId)
	{
		if ( !self::isLogged() )
		{
			$aIdentity = Zend_Auth::getInstance()->getIdentity();
			$aIdentity['Admin_id'] = $iAdminId;
			$oAuthStorage = Zend_Auth::getInstance()->getStorage();
			$oAuthStorage->write($aIdentity);
		}
	}

	/**
	 * Performs admin logout
	 *
	 */
	public static function logout()
	{
		if ( self::isLogged() )
		{
			$aIdentity = Zend_Auth::getInstance()->getIdentity();
			unset($aIdentity['Admin_id']);
			$oAuthStorage = Zend_Auth::getInstance()->getStorage();
			$oAuthStorage->write($aIdentity);
		}
		// Zend_Auth::getInstance()->clearIdentity();
		// $oZendSession = Zend_Registry::getInstance()->get('Zend_Session_Namespace');
		// Zend_Session::destroy();
	}
	
    /**
     * Performs admin registration
     *
     * @param Zend_Form $oForm
     * @param array $aPost
     * @throws Lemar_Exception
     */
    public static function doRegister(Zend_Form $oForm, $aPost)
    {
		if ($oForm->isValid($aPost))
		{
			$oAdmin = new models_Admin();
			$oAdmin->setEmail($oForm->getValue('email'))
			      ->setPassword($oForm->getValue('password'))
			      ->setFindBy($oForm->getValue('findby'));
			
			$iAdminId = models_AdminMapper::save($oAdmin);
			
			self::setLogged($iAdminId);
		}
		else
		{
			self::setErrorMessages(Lemar_Form::getErrorMessages($oForm));
			throw new Lemar_Exception();
		}
    }
    
	/**
     * Performs admin login
     *
     * @param Zend_Form $oForm
     * @param array $aPost
     * @param bool $bRememberMe
     * @throws Lemar_Exception|Lemar_AccountExpiredException
     */
    public static function doLogin(Zend_Form $oForm, $aPost, $bRememberMe)
    {
		if ($oForm->isValid($aPost))
		{
			$oDbAdapter = Zend_Db_Table_Abstract::getDefaultAdapter();
			$oAuthAdapter = new Zend_Auth_Adapter_DbTable($oDbAdapter);
			$oAuthAdapter->setTableName('admin')
			             ->setIdentityColumn('email')
			             ->setCredentialColumn('password');
			
			$oAuthAdapter->setIdentity($oForm->getValue('email'))
			             ->setCredential($oForm->getValue('password'));
			
			$oResult = $oAuthAdapter->authenticate();
			
			if (! $oResult->isValid())
			{
				// Auth doesn't have own translator. Uses translators directly
				// @var $oTranslate Zend_Translate
				$oTranslate = Zend_Registry::get('Zend_Translate');

				$aAuthErrorMessages = array();

				$sControlIndex = (Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID == $oResult->getCode()) ? '#password' : '#email';

				$aAuthErrorMessages[0][] = $sControlIndex;
				$aAuthErrorMessages[0][] = $oTranslate->translate($oResult->getCode());
				$aAuthErrorMessages[0][] = 'error';

				self::setErrorMessages($aAuthErrorMessages);
				throw new Lemar_Exception();
			}
			else
			{
				// Store auth object in storage (in session by default)
				$stdClassAdmin = $oAuthAdapter->getResultRowObject();
				Lemar_Admin::setLogged($stdClassAdmin->id);
				
				if ($bRememberMe)
				{
					Zend_Session::rememberMe();
				}
			}
		}
		else
		{
			self::setErrorMessages(Lemar_Form::getErrorMessages($oForm));
			throw new Lemar_Exception();
		}
    }
}
